/**
 * 
 */
package de.oszimtcc.timetableservices;

import java.net.UnknownHostException;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import de.oszimtcc.framework.Logger;
import de.oszimtcc.timetable.TimetableApplication;
import de.oszimtcc.timetablecore.Timetable;

/*
 * Author Kooki
 */
public class ApiRequestService extends IntentService
{

	private int	result	= Activity.RESULT_CANCELED;

	public ApiRequestService()
	{
		super("ApiRequestService");
	}

	@Override
	protected void onHandleIntent(Intent intent)
	{
		Timetable requested = null;
		String urlPath = intent.getStringExtra("url");
		String line = null;
		try 
		{
			Logger.Debug("Start Request");
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(urlPath);
			Logger.Debug("HttpPost transmitted");
			
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			line = EntityUtils.toString(httpEntity);
			requested = new Timetable(line);
			Logger.Debug("Got API-XML");
			result = Activity.RESULT_OK;

		} 
		catch (UnknownHostException e) 
		{
			Logger.Error("Error while API-Request : ",e);
			result = Activity.RESULT_CANCELED;
		}
		catch(Exception e)
		{
			Logger.Error("Error while Creating Timetable after Request : " + e);
			result = Activity.RESULT_CANCELED;
		}

		Bundle extras = intent.getExtras();
		if(extras != null)
		{
			Messenger messenger = (Messenger)extras.get("MESSENGER");
			Message msg = Message.obtain();
			msg.arg1 = result;
			msg.obj = requested;
			try
			{
				messenger.send(msg);
			}
			catch(android.os.RemoteException e1)
			{
				Logger.Error("Exception sending message", e1);
			}

		}
	}
		
	/**
	 * Function to get an XML from web
	 * @param pHandler the handler to inform about request status
	 */
	private static void StartAsynchRequest(final Handler pHandler) 
	{
		Logger.Debug("ASynch Request was called");
		Runnable r = new Runnable() 
		{
			@Override
			public void run() 
			{
				String line = null;
				try 
				{
					Logger.Debug("Start Request");
					DefaultHttpClient httpClient = new DefaultHttpClient();
					HttpPost httpPost = new HttpPost("http://api.j-moebis.de/schedule/1-0/index.php?Klasse="+ TimetableApplication.getInstance().getActivity().GetStringPreference("Class"));
					Logger.Debug("HttpPost transmitted");
					
					HttpResponse httpResponse = httpClient.execute(httpPost);
					HttpEntity httpEntity = httpResponse.getEntity();
					line = EntityUtils.toString(httpEntity);
					Logger.Debug("Got API-XML");
					
					Message msg = new Message();
					
					msg.obj = new Timetable(line);
					pHandler.sendMessage(msg);
					Logger.Debug("Handlermessage sended");
				} 
				catch (UnknownHostException e) 
				{
					Logger.Error("Error while API-Request : ",e);
					pHandler.sendEmptyMessage(-1);
				}
				catch(Exception e)
				{
					Logger.Error("Error while Creating Timetable after Request : " + e);
					pHandler.sendEmptyMessage(-2);
				}
			}
		};
		Thread t = new Thread(r);
		t.start();
		Logger.Debug("RequestThread started");
	}
	
	private static String GetRandomChangePlan()
	{
		Random rand = new Random();
		String[] lehrerarray = {"Reuter","Test","Mustermann","Langweiler","Frau","Mann","SchifffahrtSEXperte"};
		String[] geschlechter = {"Hr.","Fr.","Es."};
		String[] faecher = {"AS","BP","AS_L","BP_P","Sport","WSK","ITS","ITS_L","TEN"};
    	return "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <schedule date=\"18.05.2012\"><Monday><block nr=\"0\" canceled=\"FALSE\" lesson=\"TRUE\"><subject change=\"TRUE\"> "+ faecher[rand.nextInt(faecher.length)] + " </subject><room change=\"TRUE\"> "+ (rand.nextInt(4)+1) + "." + (rand.nextInt(4)+1) + "." + (rand.nextInt(4)+1) + "." + (rand.nextInt(99)+1) + " </room><teacher change=\"TRUE\"> "+ geschlechter[rand.nextInt(geschlechter.length)]+lehrerarray[rand.nextInt(lehrerarray.length)] + " </teacher></block><block nr=\"1\" canceled=\"TRUE\" lesson=\"TRUE\"><subject change=\"TRUE\"> "+ faecher[rand.nextInt(faecher.length)] + " </subject><room change=\"TRUE\"> "+ (rand.nextInt(4)+1) + "." + (rand.nextInt(4)+1) + "." + (rand.nextInt(4)+1) + "." + (rand.nextInt(99)+1) + " </room><teacher change=\"TRUE\"> "+ geschlechter[rand.nextInt(geschlechter.length)]+lehrerarray[rand.nextInt(lehrerarray.length)] + " </teacher></block><block nr=\"2\" canceled=\"FALSE\" lesson=\"FALSE\"><subject change=\"TRUE\"> "+ faecher[rand.nextInt(faecher.length)] + " </subject><room change=\"TRUE\"> "+ (rand.nextInt(4)+1) + "." + (rand.nextInt(4)+1) + "." + (rand.nextInt(4)+1) + "." + (rand.nextInt(99)+1) + " </room><teacher change=\"TRUE\"> "+ geschlechter[rand.nextInt(geschlechter.length)]+lehrerarray[rand.nextInt(lehrerarray.length)] + " </teacher></block></Monday><Tuesday></Tuesday><Wednesday></Wednesday><Thursday></Thursday><Friday></Friday></schedule>";
	}
}
